package busuanzi.util;

import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.Random;
import java.util.UUID;

/**
 * Auth: bruce-sha
 * Date: 2015/4/30
 */
public abstract class UUIDs {

    public static String u_u_i_d() {
        return UUID.randomUUID().toString();
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String randomLong() {
        return Long.toHexString(new Random().nextLong());
    }

    public static String uuidUpperCase() {
        return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
    }

    public static synchronized long uuidMilliseconds() {
        return System.currentTimeMillis();
    }

    public static String uuidURLEncoder() {
        String uuidStr = UUID.randomUUID().toString();
        Base64.Encoder base64 = Base64.getUrlEncoder();
        UUID uuid = UUID.fromString(uuidStr);
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());
        return base64.encodeToString(bb.array());
    }

    public static String uuidURLDecoder(String uuidStr) {
        Base64.Decoder base64 = Base64.getUrlDecoder();
        byte[] bytes = base64.decode(uuidStr);
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        UUID uuid = new UUID(bb.getLong(), bb.getLong());
        return uuid.toString();
    }

    public static void main(String[] args) {

        System.out.println(randomLong());

        String u = uuidURLEncoder();
        System.out.println(u);

        System.out.println(uuidURLDecoder(u));

    }
}
